<?php

namespace app\modules\admin\controllers;

use app\common\services\StaticServices;
use app\models\CommissionLog;
use app\models\Recommend;
use app\models\User;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Yii;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\Response;

class RecommendController extends Controller
{
    public function actionIndex()
    {
        $p = Yii::$app->request->get('p', 1);
        $recommend_info = Recommend::find();

        $page_size = StaticServices::$page;
        $total_count = $recommend_info->count();
        $total_page = ceil($total_count / $page_size);

        $list = $recommend_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->all();

        return $this->render('index', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
    }

    public function actionOps()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $recommend_id = intval(Yii::$app->request->post('recommend_id'));
                if (!$recommend_id) {
                    throw new Exception('参数有误');
                }
                Recommend::deleteAll(['id' => $recommend_id]);
                return ['code' => 200, 'msg' => '操作成功'];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
    }

    public function actionCommission()
    {
        $p = Yii::$app->request->get('p', 1);
        $recommend_info = Recommend::find()->where(['recommend_type' => 6]);

        $page_size = StaticServices::$page;
        $total_count = $recommend_info->count();
        $total_page = ceil($total_count / $page_size);

        $list = $recommend_info->offset(($p - 1) * $page_size)->orderBy(['update_time' => SORT_DESC])->limit($page_size)->all();

        return $this->render('commission', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
    }

    public function actionSetCommission()
    {
        $recommend_id = Yii::$app->request->get('id');
        $commission_info = [];
        if ($recommend_id) {
            $commission_info = Recommend::find()->where(['id' => $recommend_id, 'recommend_type' => 6])->one();
        }

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $recommend_id = intval(Yii::$app->request->post('recommend_id'));
                $recommend_commission = intval(Yii::$app->request->post('recommend_commission'));
                $func = Yii::$app->request->post('func');
                if (!$recommend_id) {
                    throw new Exception('参数有误');
                }

                if ($func == 'set_commission') {
                    $recommend_arr = Recommend::find()->where(['id' => $recommend_id, 'recommend_source' => 1])->one();
                    if (!$recommend_arr) {
                        throw new Exception('更改数据有误');
                    }
                    $recommend_arr->recommend_commission = $recommend_commission;
                    $recommend_arr->commission_status = 1;
                    $recommend_arr->update_time = time();
                    if ($recommend_arr->save(0)) {
                        $commission_log = new CommissionLog();
                        $commission_log->recommend_id = $recommend_arr->recommend_id;
                        $commission_log->recommend_commission = $recommend_commission;
                        $commission_log->update_time = time();
                        $commission_log->create_time = time();
                        $commission_log->save(0);
                        $user_info = User::find()->where(['id' => $recommend_arr->recommend_id])->one();
                        $user_info->commission += $recommend_commission;
                        $user_info->update_time = time();
                        $user_info->save(0);
                        return ['code' => 200, 'msg' => '操作成功'];
                    }
                }

                $recommend_info = Recommend::find()->select('id,member_name,recommend_name')->where(['id' => $recommend_id, 'recommend_source' => 1])->asArray()->one();
                if (!$recommend_info) {
                    throw new Exception('数据有误');
                }
                return ['code' => 200, 'msg' => '操作成功', 'data' => $recommend_info];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
        return $this->render('set_commission', ['info' => $commission_info]);
    }

    public function actionEditor()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $recommend_id = intval(Yii::$app->request->post('recommend_id'));
                $commission_status = intval(Yii::$app->request->post('commission_status'));
                $recommend_log_id = intval(Yii::$app->request->post('recommend_log_id'));

                if (!$recommend_id) {
                    throw new Exception('参数有误');
                }
                if ($commission_status != 1) {
                    throw new Exception('佣金状态有误');
                }
                $recommend_info = Recommend::find()->where(['id' => $recommend_id, 'recommend_type' => 6])->one();
                if (!$recommend_info) {
                    throw new Exception('数据有误');
                }
                $recommend_info->commission_status = 2;
                $recommend_info->update_time = time();
                if ($recommend_info->save(0)) {
                    $commission_log = CommissionLog::find()->where(['recommend_id' => $recommend_log_id])->one();
                    $commission_log->commission_status = 1;
                    $commission_log->update_time = time();
                    $commission_log->update(0);
                    return ['code' => 200, 'msg' => '操作成功'];
                }
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
    }

    public function actionSet()
    {
        $re_id = Yii::$app->request->get('id', 0);
        $re_info = [];

        //获取所以经纪人
        $users = User::find()->where(['user_role' => 3])->asArray()->all();
        $user_arr = [];
        foreach ($users as $item) {
            $user_arr[$item['id']] = $item['user_name'];
        }
        if ($re_id) {
            $re_info = Recommend::find()->where(['id' => $re_id])->one();
        }

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $opertion_id = intval(Yii::$app->request->post('opertion_id'));
                $re_id = intval(Yii::$app->request->post('re_id'));
                if (!$opertion_id) {
                    throw new Exception('参数有误1');
                }
                if (!$re_id) {
                    throw new Exception('参数有误2');
                }
                $recommend_info = Recommend::find()->where(['id' => $re_id])->one();
                if (!$recommend_info) {
                    throw new Exception('数据有误');
                }
                $recommend_info->opertion_id = $opertion_id;
                $recommend_info->opertion_name = $user_arr[$opertion_id];
                $recommend_info->recommend_type = 9;
                $recommend_info->update_time = time();
                $recommend_info->save(0);
                return ['code' => 200, 'msg' => '修改成功'];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
        return $this->render('set', ['info' => $re_info, 'user_arr' => $user_arr]);
    }

    public function actionUpload()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                $file_path = trim(Yii::$app->request->post('file_path'));
                $header = IOFactory::createReader('Xlsx');
                $header->setReadDataOnly(true);
                $spreadsheet = $header->load(Yii::$app->getBasePath() . '/web' . $file_path); // 加载Excel表格

                $worksheet = $spreadsheet->getActiveSheet();
                $total_row = $worksheet->getHighestRow(); //总行数
                $total_column = $worksheet->getHighestColumn(); //总列数
                $highestColumnindex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($total_column);
                if ($total_row <= 0) {
                    exit('excel表中没有数据');
                }
                $import_info = [];
                for ($row = 2; $row <= $total_row; $row++) {
                    $member_name = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //获取被推荐人姓名
                    $member_phone = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //获取被推荐人电话
                    $recommend_name = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //获取推荐人姓名
                    $recommend_phone = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //获取推荐码人电话
                    $remark = $worksheet->getCellByColumnAndRow(5, $row)->getValue(); //获取备注信息
                    if (!preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $member_phone) || !preg_match('/^(0|86|17951)?(1[356789])[0-9]{9}$/', $recommend_phone)) {
                        throw new Exception('请填写正确的手机号码~~~~');
                    }
                    //通过检索用户电话，检查此用户是否已经被推荐
                    $member_info = \app\models\Member::find()->where(['member_phone' => $member_phone])->one();
                    if ($member_info) {
                        throw new Exception('用户数据错误,请核实后再导入');
                    }
                    //检查推荐人的身份

                    $recommend_info = User::find()->where(['user_phone' => $recommend_phone])->one();
                    if (!$recommend_info) {
                        throw new Exception('推荐人数据错误,请核实后再导入');
                    }

                    //将检查正确的数据添加进数组中
                    $data = [
                        'member_name' => $member_name,
                        'member_phone' => $member_phone,
                        'recommend_name' => $recommend_name,
                        'recommend_phone' => $recommend_phone,
                        'remark' => $remark,
                    ];
                    array_push($import_info, $data);
                }
                if (!$import_info) {
                    throw new Exception('数据有误，请核对后再导入');
                }

                //将被推荐人入库

                foreach ($import_info as $value) {
                    $member = new \app\models\Member();
                    $member->member_name = $value['member_name'];
                    $member->member_phone = $value['member_phone'];
                    $member->recommend_id = $recommend_info->id;
                    $member->update_time = time();
                    $member->create_time = time();
                    $member->save(0);
                    //将用户和推荐人信息添加到推荐表中
                    $recommend = new Recommend();
                    $recommend->member_id = $member->id;
                    $recommend->member_name = $value['member_name'];
                    $recommend->recommend_id = $recommend_info->id;
                    $recommend->recommend_name = $value['recommend_name'];
                    $recommend->recommend_source = 1;
                    $recommend->remark = $value['remark'];
                    $recommend->update_time = time();
                    $recommend->create_time = time();
                    $recommend->save(0);
                }
                return ['code' => 200, 'msg' => '导入成功'];
            } catch (Exception $e) {
                return ['code' => -200, 'msg' => $e->getMessage()];
            }
        }
    }
}